package com.topsoft.micro.config.oauth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;


/**
 *  配置资源认证
 * @author Administrator
 *@Configuration
@EnableResourceServer
 */
@Configuration
@EnableResourceServer	
public class MyResourceServerConfig extends ResourceServerConfigurerAdapter{
	
private static final String SERVER_RESOURCE_ID = "MyOauth2Server";
	
	@Autowired
	private TokenStore  redisTokenStore;
	 
	 
	 @Override
	 public void configure(ResourceServerSecurityConfigurer resources) {
				//resourceId 用于分配给可授予的clientId
				//stateless  标记以指示在这些资源上仅允许基于令牌的身份验证
				//tokenStore token的存储方式（上一章节提到）
	         resources.resourceId(SERVER_RESOURCE_ID).stateless(false).tokenStore(redisTokenStore);
					//authenticationEntryPoint  认证异常流程处理返回
					//tokenExtractor            token获取方式,默认BearerTokenExtractor 
					//                         从header获取token为空则从request.getParameter("access_token")
	              //.authenticationEntryPoint(authenticationEntryPoint).tokenExtractor(unicomTokenExtractor);
	     }

	 /**
	  * 配置哪些restful接口需要 认证,  以及权限表达式
	  */
	@Override
	public void configure(HttpSecurity http) throws Exception {
		System.out.println("====================ResourceServerConfiguration.configure(HttpSecurity http)===================== ");
		
		http
			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
				.and()
			.requestMatchers()
				.antMatchers("/user/**")   //只匹配/user/下面的
				.and()
            .authorizeRequests()
                .antMatchers("/user/**").access("#oauth2.hasScope('all') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")
                .anyRequest().authenticated();
            //.antMatchers("/user/**").permitAll();
	}


}
